import React, { useEffect } from 'react';
import { connect } from 'react-redux'
import { URL_API, fetchUsersStarted, fetchUsers } from '../context/Actions';
import { FlatList, View, Text, StyleSheet } from 'react-native';
import UserListItem from './UserListItem';

const UsersList = (props) => {

    const { loading, error, data } = props.users;
    useEffect(() => {
        props.fetchUsersStarted();//dispatch(fetchUsersStarted());
        const url = `${URL_API}/users`;
        const request = {};
        props.fetchUsers(url, request);
    }, []);
    if (loading === true) {
        return (
            <View style={styles.item}>
                <Text>Loading ....</Text>
            </View>
        );
    }
    else {
        if (error !== null) {
            return (
                <View style={styles.item}>
                    <Text>Error ....</Text>
                </View>
            );
        } else {
            if (data.length > 0) {
                return (
                    <FlatList
                        data={data}
                        keyExtractor={(item) => item.id.toString()}
                        renderItem={({ item }) => (
                            <UserListItem
                                item={item} />
                        )}
                    />
                );
            } else {
                return (
                    <View style={styles.item}>
                        <Text>No data ....</Text>
                    </View>
                );
            }
        }
    }
}
const styles = StyleSheet.create({
    item: {
        borderTopWidth: 2,
        borderBottomWidth: 2,
        borderColor: "black"
    },
});
const mapStateToProps = (state) => {
    return {users: state.users};
}
const mapDispatchToProps = (dispatch) => {
    return {
        fetchUsers: (url, request) => fetchUsers(url, request, dispatch),
        fetchUsersStarted: () => dispatch(fetchUsersStarted()),
       
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(UsersList)
